// 获取元素信息
function getRect(selector) {
  return new Promise((resolve) => {
    wx.createSelectorQuery()
      .in(this)
      .select(selector)
      .boundingClientRect()
      .exec((rect = []) => resolve(rect[0]))
  })
}
// 获取集合元素信息
function getAllRect(selector) {
  return new Promise((resolve) => {
    wx.createSelectorQuery()
      .in(this)
      .selectAll(selector)
      .boundingClientRect()
      .exec((rect = []) => resolve(rect[0]))
  })
}

// 滚动到指定元素
function getCenterViewDy(toParams) {
  if (!toParams) {
    return
  }
  const {
    index // 当前索引
    , listClass // scroll-view class或者 id
    , itemClass // scroll-view 子元素item class
  } = toParams
  const vm = this
  return Promise.all([
    getAllRect.call(vm, itemClass),
    getRect.call(vm, listClass)
  ]).then(([tabRects, navRect]) => {
    const tabRect = tabRects[index]
    const offsetLeft = tabRects
      .slice(0, index)
      .reduce((prev, curr) => prev + curr.width, 0)
    const dy = offsetLeft - (navRect.width - tabRect.width) / 2
    return Promise.resolve({ dy })
  })
}

module.exports = {
  getRect,
  getAllRect,
  getCenterViewDy
}
